from bs4 import BeautifulSoup

# Tag 标签，基本信息组织单元，分别用<>和</>标明开头和结尾
# Name 标签的名字，<p></p>的名字是‘p’，格式：<tag>.name
# Attributes 标签的属性，字典形式组织，格式：<tag>.attrs
# NavigableString 标签内非属性字符串，<>...<>中字符串，格式：<tag>.string
# Comment 标签内字符串的注释部分，一种特殊的 Comment 类型

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
</body>
</html>
"""

soup = BeautifulSoup(html, 'lxml')
print('按照标准缩进形式输出：')
print(soup.prettify())
print('输出标题内容：')
print(soup.title.string)
print('输出head信息')
print(soup.head)
print('输出p标签内的内容')
print(soup.p)
print('获取title的name属性：')
print(soup.title.name)
print('获取p标签的所有属性值：')
print(soup.p.attrs)
print('获取p标签的name属性值：')
print(soup.p.attrs['name'])

html2 = """<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<p class="story">
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">
<span>Elsie</span>
</a>
hello 
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a>
and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>
and they lived at the bottom of a well. </p>
<p class="story">...</p>"""
soup = BeautifulSoup(html2, 'lxml')
print('获取p标签children属性')
print(soup.p.children)
for i, child in enumerate(soup.p.children):
    print(i, child)
print('获取a标签的parent')
print(soup.a.parent)
print('获取a标签的parents')
print(soup.a.parents)
for i, parent in enumerate(soup.p.parents):
    print(i, parent)
# 调用 next_sibling 和 previous_sibling 分别获取节点的下一个和上一个兄弟元素
print('调用 next_sibling 和 previous_sibling 分别获取节点的下一个和上一个兄弟元素')
print('next_sibling:', soup.a.next_sibling)
print('previous_sibling:', soup.a.previous_sibling)
